<template>
  <div :class="$options.name">
    <el-upload
      v-if="imgType !== 'tinymce'"
      v-show="!resultImg"
      ref="fileUpload"
      :action="action"
      :data="uploadData"
      :on-change="selectChange"
      :show-file-list="false"
      :auto-upload="false"
      :disabled="disabled"
      :http-request="httpRequest"
      :with-credentials= "false"
      class="upload-el editor-slide-upload"
      accept="image/*"
      name="pic">
      <div>
        <span
          class="icon upload-icon" />
        <el-button size="small" type="primary">选择图片</el-button>
      </div>
      <!-- <div
        slot="tip"
        class="el-upload__tip">
        图片大小不超过5M，推荐图片尺寸宽高比9:16
      </div> -->
    </el-upload>

    <!-- <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        class="editor-slide-upload"
        list-type="picture-card">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload> -->
    <!-- 多张上传 -->
    <el-upload
      v-if="imgType === 'tinymce'"
      v-show="!resultImg"
      ref="fileUpload"
      :multiple="true"
      :action="action"
      :data="uploadData"
      :on-change="selectChange"
      :on-remove="remove"
      :file-list="fileList"
      :show-file-list="true"
      :auto-upload="false"
      :http-request="httpRequest"
      :with-credentials= "false"
      list-type="picture-card"
      class="upload-el editor-slide-upload"
      accept="image/*"
      name="pic">
      <div>
        <span
          class="icon upload-icon" />
        <el-button size="small" type="primary">选择图片</el-button>
      </div>
      <!-- <div
        slot="tip"
        class="el-upload__tip">
        图片大小不超过5M，推荐图片尺寸宽高比9:16
      </div> -->
    </el-upload>
    <figure
      v-show="resultImg"
      class="result-img">
      <img
        :src="resultImg">
      <el-button
        @click="updateCropper">重新上传</el-button>
    </figure>
    <cropper
      v-if="showCropper"
      :dialog-visible="showCropper"
      :cropper-img="cropperImg"
      :fixed-number="fixedNumber"
      :progress-flag="progressFlag"
      :load-progress="loadProgress"
      @update-cropper="updateCropper"
      @colse-dialog="closeDialog"
      @upload-img="uploadImg" />
  </div>
</template>

<script>
import config from '@/utils/config';
import Cropper from '@/components/cropper/uploadImage'
// import { baseAxios } from '@common/axios';
// import { loading } from '@common';
import axios from 'axios'
import { Message } from 'element-ui';
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
export default {
  name: 'UploadImg',
  components: {
    Cropper
  },
  props: {
    imgType: {
      type: String,
      default: ''
    },
    fixedNumber: {
      type: Array,
      default: () => {
        return [16, 9]
      }
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data() {
    return {
      progressFlag: false,
      loadProgress: 0,
      uploadData: { // 上传需要的额外参数
        siteId: 1,
        source: 1
      },
      fileList: [],
      action: 'http://qiniu.kyzhiban.cn',
      cropperImg: '', // 需要裁剪的图片
      showCropper: false, // 是否显示裁剪框
      uploadFile: '', // 裁剪后的文件
      resultImg: '' // 上传成功，后台返回的路径
    };
  },
  methods: {
    remove(val) {
      // console.log('图片删除', val)
      this.$emit('removePic', val)
      // console.log(this.fileList)
      const index = this.fileList.findIndex(res => res.uid === val.uid)
      this.fileList.splice(index, 1)
      // console.log(index)
    },
    removeAll() {
      this.fileList = []
    },
    base64ToFile(urlData, fileName) {
      const arr = urlData.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bytes = atob(arr[1]); // 解码base64
      let n = bytes.length
      const ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
    },
    // submit 之后会触发此方法
    httpRequest(request) {
      // console.log('请求多次??????')
      const { action, data, filename, file } = request;
      //   console.log('action:', action)
      //   console.log('data:', data)
      //   console.log('filename:', filename)
      // console.log('request', request)
      // 新建formDate对象
      const formData = new FormData();
      for (const key in data) {
        formData.append(key, data[key]);
      }
      // console.log(this.uploadFile)
      // 文件单独push,第三个参数指定上传的文件名
      // formData.append(filename, this.uploadFile, data.fileName);

      console.log('this.uploadFile:', this.uploadFile)
      //   console.log('filename:', filename)
      // console.log('this.uploadFile:::', this.uploadFile)
      //   console.log('file:', file)
      // const blobToFiles = new window.File([this.uploadFile], file.name, { type: file.type })
      const blobToFiles = new File([this.uploadFile], file.name, { type: file.type, lastModified: Date.now() });
      // console.log(blobToFiles)
      console.log(file.type)
      const fileType = file.type.split('/')[1]
      const keyname = `${new Date().getTime()}${Math.random().toString(36).slice(2)}.${fileType}`
      const token = GetQiniuToken().uploadToken
      formData.append('file', blobToFiles);
      formData.append('key', keyname);
      formData.append('token', token);
      // loading.start(); // 上传中的loading
      axios({
        headers: {
          contentType: 'multipart/form-data' // 需要指定上传的方式
        },
        url: 'https://up-z1.qiniup.com',
        method: 'post',
        data: formData,
        timeout: 200000, // 防止文件过大超时
        onUploadProgress: progressEvent => {
          this.progressFlag = true; // 显示进度条
          const complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
          // console.log(complete)
          this.loadProgress = complete
        }
      }).then(res => {
        console.log('图片上传返回值::', res)
        if (res.status === 200) {
          this.progressFlag = false;
          Message.success('图片上传成功')
          if (this.imgType === 'tinymce') {
            this.fileList.push({
              'id': res.data.data.id,
              'name': file.name,
              'type': file.type,
              'url': 'http://qiniu.kyzhiban.cn' + res.data.key
            })
            this.$emit('modalShowFn', 'http://ht.ma3u.com/' + res.data.key)
            request.onSuccess()

            // alert(111)
          } else {
            this.$emit('modalShowFn', 'http://ht.ma3u.com/' + res.data.key)
            // alert(22)
          }
          // if (this.imgType === 'tinymce') this.$emit('modalShowFn', res.data)
        } else {
          Message.error(res.message || '网络错误...');
        }
        this.showCropper = false
      }).catch(err => {
        // loading.close();
        console.log(err);
      });
    },
    // 选择文件
    selectChange(file) {
      const { raw } = file;
      this.openCropper(raw);
    },
    /**
     * @param {file} 上传的文件
      */
    openCropper(file) {
      this.cropperImg = ''
      var files = file;
      const isLt5M = files.size > (5 << 20);
      if (isLt5M) {
        this.$message.error('请上传5M内的图片');
        return false;
      }
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropperImg = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(files);
      this.showCropper = true;
    },
    // 上传图片
    uploadImg(file) {
      console.log('imgType:::::', this.imgType)
      this.uploadFile = file;
      this.$refs.fileUpload.submit();
    },
    // 更新图片
    updateCropper() {
      this.$refs.fileUpload.$children[0].$el.click();
    },
    // 关闭窗口
    closeDialog(val) {
      this.showCropper = false;
      // const index = this.fileList.findIndex(res => res.uid === val.uid)
      console.log(this.fileList.length - 1)
      // this.fileList.splice((this.fileList.length - 1), 1)
    }
  }
};
</script>

<style lang="scss" scoped>
.UploadImg {
  .video-image {
    display: flex;
    figure {
      width: 100px;
      img {
        width: 100%;
        display: block;
      }
    }
  }
}
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>
